//
//  FotoNou.m
//  iDent
//
//  Created by Marius Corega on 6/15/09.
//  Copyright 2009 Marius Corega. All rights reserved.
//


#import "Controller.h"
#import "DatatoDataView.h"

@implementation Controller (FotoNou)

-(IBAction) addFoto:(id)sender
{
	[fotoNouData setDateValue:[NSDate date]];
	[NSApp beginSheet:fotoNouWindow modalForWindow:window modalDelegate:self didEndSelector:@selector(newObjectSheetDidEnd:returnCode:contextInfo:) contextInfo:NULL];
}

- (NSData*)generateFormData:(NSDictionary*)dict
{
	NSString* boundary = [NSString stringWithString:@"_insert_some_boundary_here_"];
	NSArray* keys = [dict allKeys];
	NSMutableData* result = [[NSMutableData alloc] initWithCapacity:100];
	
	int i;
	for (i = 0; i < [keys count]; i++) 
	{
		id value = [dict valueForKey: [keys objectAtIndex: i]];
		[result appendData:[[NSString stringWithFormat:@"--%@\n", boundary] dataUsingEncoding:NSASCIIStringEncoding]];
/*		if ([value class] == [NSString class]  )
		{
			[result appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\n\n", [keys objectAtIndex:i]] dataUsingEncoding:NSASCIIStringEncoding]];
			[result appendData:[[NSString stringWithFormat:@"%@",value] dataUsingEncoding:NSASCIIStringEncoding]];

		}
 */
		if ([value class] == [NSURL class] && [value isFileURL])
		{
			[result appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\n", [keys objectAtIndex:i], [[value path] lastPathComponent]] dataUsingEncoding:NSASCIIStringEncoding]];
			[result appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\n\n"] dataUsingEncoding:NSASCIIStringEncoding]];
			[result appendData:[NSData dataWithContentsOfFile:[value path]]];
		}
		else
		{
			[result appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\n\n", [keys objectAtIndex:i]] dataUsingEncoding:NSASCIIStringEncoding]];
			[result appendData:[[NSString stringWithFormat:@"%@",value] dataUsingEncoding:NSASCIIStringEncoding]];
		
		}
		[result appendData:[[NSString stringWithString:@"\n"] dataUsingEncoding:NSASCIIStringEncoding]];
	}
	[result appendData:[[NSString stringWithFormat:@"--%@--\n", boundary] dataUsingEncoding:NSASCIIStringEncoding]];
	
	return [result autorelease];
}


- (void)newObjectSheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode  contextInfo:(void  *)contextInfo
{	
	if ((returnCode == NSOKButton) && (fotoNouURL != nil))
	{
		NSMutableDictionary *pp = [pacienti selectedElement];
		NSMutableDictionary* post_dict = [[NSMutableDictionary alloc] init];

		NSInteger tip_foto_idx = [fotoNouTipFoto indexOfSelectedItem];
	//	NSString *tip_foto = [NSString stringWithFormat:@"%d", tip_foto_idx];
		
		[post_dict setObject:[pp objectForKey:@"id"] forKey:@"pacientid"];
		[post_dict setObject:[[DatatoDataView alloc] reverseTransformedValue:[fotoNouData dateValue]] forKey:@"data"];
		[post_dict setObject:[[NSNumber numberWithInt:tip_foto_idx] stringValue]  forKey:@"tip"];
		[post_dict setObject:[fotoNouDescriere stringValue] forKey:@"descriere"];
		[post_dict setObject:fotoNouURL forKey:@"file"];

	//	[poze addElement:post_dict];
		
		
		NSData* regData = [self generateFormData:post_dict];
		[post_dict release];
	
		NSMutableString *srvURL = [[NSMutableString alloc] initWithString:serverURL];		
		[srvURL appendString:@"incarcaimagine.php"];
		
		
		NSMutableURLRequest* post = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:srvURL]];
		[post addValue: @"multipart/form-data; boundary=_insert_some_boundary_here_" forHTTPHeaderField: @"Content-Type"];
		[post setHTTPMethod: @"POST"];
		[post setHTTPBody:regData];
		NSURLResponse* response;
		NSError* error;
		NSData* result = [NSURLConnection sendSynchronousRequest:post returningResponse:&response error:&error];
		NSLog(@"%@", [[[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding] autorelease]);
		
	}
	
	[fotoNouWindow orderOut:self];
	return;
}

-(IBAction) addFotoOK:(id)sender
{
	[NSApp endSheet:fotoNouWindow returnCode:NSOKButton];
	[self loadFotoForPacient:[[pacienti selectedElement] objectForKey:@"id"] forceReload:YES];
}

-(IBAction) addFotoCancel:(id)sender
{
	[NSApp endSheet:fotoNouWindow returnCode:NSCancelButton];	
}

-(IBAction) openFoto:(id)sender
{
	NSOpenPanel *op = [NSOpenPanel openPanel];
	NSArray *ft = [NSArray arrayWithObjects:@"jpg", @"jpeg", @"bmp", @"tif", @"tiff",@"gif",nil];
	
	
	if([op runModalForTypes:ft] == NSOKButton)
	{
		NSArray *res = [op URLs];
		fotoNouURL = [[res objectAtIndex:0] copy];
		
		NSImage *img = [[NSImage alloc] initWithContentsOfURL:fotoNouURL];
		
		[fotoNouIV setImage:img];
	}
}

@end
